import { reqgetbanner, reqgetindexgoods, reqgetnew } from "../../http/api";

//State
const initState = {
    getnew: [],
    banner: [],
    indexgoods: [],
    n: 0
}
//action type 
const TYPES = {
    HOME_CHANGE_BANNER: "HOME_CHANGE_BANNER",
    HOME_CHANGE_GOODS: "HOME_CHANGE_GOODS",
    HOME_CHANGE_N: "HOME_CHANGE_N",
    HOME_CHANGE_GETNEW: "HOME_CHANGE_GETNEW"
}
//reducer
const reducer = (state = initState, action) => {
    switch (action.type) {
        case TYPES.HOME_CHANGE_BANNER:
            return {
                ...state,
                banner: action.banner
            }
        
        case TYPES.HOME_CHANGE_GOODS:
            return {
                ...state,
                indexgoods: action.indexgoods
            }
        case TYPES.HOME_CHANGE_N:
            return {
                ...state,
                n: action.n

            }
        case TYPES.HOME_CHANGE_GETNEW:
            return {
                ...state,
                getnew: action.getnew
            }
        default:
            return state;
    }
}
//action creator
export const actions = {
    changeBanner: (banner) => ({ type: TYPES.HOME_CHANGE_BANNER, banner }),
    // 请求banner的action
    reqBanner: () => (dispatch, getState) => {
        reqgetbanner().then(res => {
            // 修改banner
            dispatch(actions.changeBanner(res.data.list))
        })
    },
    //   触发goods的action
    changeGoods: (indexgoods) => ({ type: TYPES.HOME_CHANGE_GOODS, indexgoods }),
    // 请求goods的action
    reqGoods: () => (dispatch, getState) => {
        reqgetindexgoods().then(res => {
            dispatch(actions.changeGoods(res.data.list))
        })
    },
    //   触发n的action
    changeN: n => ({ type: TYPES.HOME_CHANGE_N, n }),
    // 触发getnew的action
    changegetnew: (getnew) => ({ type: TYPES.HOME_CHANGE_GETNEW, getnew }),
    reqnew: () => (dispatch, getState) => {
        reqgetnew().then(res => {
            dispatch(actions.changegetnew(res.data.list))
        })
    }

}

//selector导出数据给组件

export const getBanner = state => state.home.banner
export const getGoods = state => state.home.indexgoods
export const getN = state => state.home.n
export const getnew=state=>state.home.getnew
//导出
export default reducer;